package com.tansun.tandata.controller;


import java.util.List;

import javax.validation.Valid;

import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.tansun.tandata.entity.OrgInfo;
import com.tansun.tandata.service.OrgInfoService;
import com.tansun.tandata.service.UserService;
import com.tansun.tandata.utils.BeanUtil;
import com.tansun.tandata.utils.Constants;
import com.tansun.tandata.utils.ParentController;
import com.tansun.tandata.utils.ResponseBase;
import com.tansun.tandata.vo.req.OrgInfoAddVO;
import com.tansun.tandata.vo.req.OrgInfoUpdateVO;
import com.tansun.tandata.vo.res.OrgInfoTreeVO;
import com.tansun.tandata.vo.res.OrgInfoVO;
import com.tansun.tandata.vo.res.UserRoleVO;
import com.tansun.tjmas.cloud.base.redis.utils.RedisUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 控制层
 * @author liuyu
 * @date 2020-06-09 16:26:22
 * @Version v1.0
 */
@Api(value = "接口")
@Controller
@RequestMapping(value = "/sys/orgInfo")
public class OrgInfoController  extends ParentController {

	@Autowired
	private OrgInfoService orgInfoService;
	@Autowired
	private UserService userService;
	@Autowired
	private RedisUtils redisUtils;

	/**
     * 新增
     * @param req
     */
	@ApiOperation(value="新增", notes="新增",httpMethod = "POST")
	@PostMapping("/add")
	@ResponseBody
	public ResponseBase add(@Valid @RequestBody OrgInfoAddVO req, BindingResult bindingResult) {
		try {
			// 验证参数
			ResponseBase validResult = validateField(bindingResult);
			if (validResult != null) {
				return validResult;
			}
			//存在性验证，姓名验证
			int count = orgInfoService.getOrgInfoByOrgName(req.getOrgName());
			if (count > Constants.CHAR_INT_ZERO) {
				return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("sys.common.org.name.isExist"), null);
			}
			OrgInfo orgInfo = BeanUtil.copyProperties(req, OrgInfo.class);
			orgInfoService.insert(orgInfo);
			return setResultSuccess();
		} catch (Exception e) {
			return sysError(e);
		}
	}


	/**
     * 更新
     * @param req
     */
	@ApiOperation(value="编辑", notes="编辑",httpMethod = "PUT")
	@PutMapping("/update")
	@ResponseBody
	public ResponseBase update(@Valid @RequestBody OrgInfoUpdateVO req, BindingResult bindingResult) {
		try {
			// 验证参数
			ResponseBase validResult = validateField(bindingResult);
			if (validResult != null) {
				return validResult;
			}
			//存在性验证，姓名验证
			int count = orgInfoService.getOrgInfoByOrgNameAndCode(req.getOrgName(), req.getOrgCode());
			if (count > Constants.CHAR_INT_ZERO) {
				return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("sys.common.menu.name.isExist"), null);
			}
			OrgInfo orgInfo = BeanUtil.copyProperties(req,OrgInfo.class);
			orgInfoService.updateByOrgCode(orgInfo);
			return setResultSuccess();
		} catch (Exception e) {
			return sysError(e);
		}
	}

	/**
     * 删除
     * @param orgCode
     */
	@ApiOperation(value="删除", notes="删除",httpMethod = "DELETE")
	@DeleteMapping( "/delete")
	@ResponseBody
	public ResponseBase delete( @ApiParam(value = "orgCode", required = true) @RequestParam("orgCode") String orgCode) {
		try {
			if(orgCode == null){
				return sysNullError();
			}
			//存在性验证，如果有用户包含机构则不让删
			int count = userService.getUserByOrgCode(orgCode);
			if (count > Constants.CHAR_INT_ZERO) {
				return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("sys.common.user.org.isExist"), null);
			}
			orgInfoService.deleteByOrgCode(orgCode);
			return setResultSuccess(localeMessage.getMessage("sys.common.org.info.deleteSuccess"));
		} catch (Exception e) {
			return sysError(e);
		}
	}

	/**
     * 主键获取
     * @param orgCode
     * @return ResponseBase<OrgInfoRESP>
     */
	@ApiOperation(value="主键获取", notes="主键获取",httpMethod = "GET")
	@ApiImplicitParam(name = "orgCode", value = "orgCode", required = true, dataType = "String")
	@GetMapping("/get-by-OrgCode")
	@ResponseBody
	public ResponseBase<OrgInfoVO> getByOrgCode(String orgCode) {
		try {
			if(orgCode == null){
				return sysNullError();
			}
			OrgInfo orgInfo = orgInfoService.getByOrgCode(orgCode);
			return setResultSuccess(BeanUtil.copyProperties(orgInfo, OrgInfoVO.class));
		} catch (Exception e) {
			return sysError(e);
		}
	}
	
	@ApiOperation(value="获取当前机构的子机构", notes="根据机构编码获取此机构的子机构树")
	@ApiImplicitParam(name = "orgCode", value = "机构编码", required = true, dataType = "String")
	@GetMapping(value = "/getChildOrgByOrgCode")
	public ResponseBase<List<OrgInfoTreeVO>> getChildOrgByOrgCode(@RequestParam("orgCode") String orgCode) {
		try {
			List<OrgInfoTreeVO> orgInfoTreeVOList = orgInfoService.getChildOrgByOrgCode(orgCode);
			return setResultSuccess(orgInfoTreeVOList);
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
		}
	}
	
	@ApiOperation(value="缓存机构信息缓存到redis", notes="将所有用户子机构信息缓存到redis")
	@GetMapping(value="/getAllUserWithChildOrg2Redis")
	public ResponseBase getAllUserWithChildOrg2Redis(){
		try {
			List<UserRoleVO> users = userService.selectAllUser();
			for (UserRoleVO user : users) {
				List<OrgInfoTreeVO> orgInfoTreeVOList = orgInfoService.getChildOrgByOrgCode(user.getOrgCode());
//TODO			redisUtils.set(Constants.CHILD_ORG_REDIS+user.getUserCode(), JSONObject.parse(orgInfoTreeVOList.toString()));
				redisUtils.set(Constants.CHILD_ORG_REDIS+user.getUserCode(), JSONObject.toJSONString(orgInfoTreeVOList, SerializerFeature.WriteMapNullValue));
			}
			return setResultSuccess(localeMessage.getMessage("sys.user.put.redis.success"));
		} catch (Exception e) {
			e.printStackTrace();
			//系统错误
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
		}
	}
}
